package com.ljl.controller;

import com.ljl.Entity.AdminUser;
import com.ljl.Entity.Custom;
import com.ljl.Entity.Imgyzm;
import com.ljl.Entity.Orderlist;
import com.ljl.Mapper.AdminUserMapper;
import com.ljl.Mapper.CustomListMapper;
import com.ljl.Mapper.OrderListMapper;
import com.ljl.Mapper.YzmMapper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.management.openmbean.InvalidKeyException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Controller
@CrossOrigin(origins = "*")
public class CustomController {


    //主页
    @RequestMapping("/customIndex")
    public String customIndex() {
        return "customIndex";
    }
    //添加客户界面
    @RequestMapping("/goaddcustom")
    public String goaddcustom() {
        return "addcustom";
    }
    //添加注册界面
    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    public String img_url;
    public String jl_url;

    public String yzm_code;
    //添加客户到sql，再返回到主页
    @RequestMapping("/addcustom")
    public String addcustom(Custom custom) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("正在添加数据库");
        System.out.println("正在添加数据库");
        System.out.println("简历：" + jl_url);
        System.out.println("头像：" + img_url);
        if (custom.getName() != null) {
            SqlSessionFactory ssf = null;
            try {
                InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
                ssf = new SqlSessionFactoryBuilder().build(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SqlSession sqlSession = ssf.openSession();
            CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
            custom.setJlurl(jl_url);
            custom.setImgurl(img_url);
            System.out.println(custom.getJlurl());
            System.out.println(custom.getImgurl());
            int result_code = customListMapper.insertCustom(custom);
            sqlSession.commit();
            System.out.println("正在添加客户信息");
            if (result_code == 1) {
                System.out.println("新增客户成功！");
            }else {
                System.out.println("新增客户失败！");
            }
        }
        return "customIndex";
    }

    //获取全部客户信息
    @GetMapping(value = "selectAllCustomList", produces = "application/json")
    @ResponseBody
    public List<Custom> selectAllCustomList() {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getAllCustomList();
        System.out.println("系统正在获取所有客户信息");
        System.out.println(custom);
        return custom;
    }

    //模糊查询客户信息-根据name模糊查询
    @PostMapping(value = "selectCustomLikeName", produces = "application/json")
    @ResponseBody
    public List<Custom> selectCustomLikeName(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getOrderListByLikeCustomName(request.getParameter("CustomName"));
        System.out.println("用户正在进行模糊查询");
        return custom;
    }


    //准确查询客户信息-根据name准确查询
    @PostMapping(value = "selectCustomByName", produces = "application/json")
    @ResponseBody
    public List<Custom> selectCustomByName(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getOrderListByCustomName(request.getParameter("CustomName"));
        System.out.println("用户正在进行精确查询");
        System.out.println("用户正在进行精确查询");
        return custom;
    }

    //删除客户信息-根据id删除
    @PostMapping(value = "deleteCustomByid", produces = "application/json")
    @ResponseBody
    public int deleteCustomByid(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        System.out.println(request.getParameter("id"));
        int id = Integer.parseInt(request.getParameter("id"));
        int code = customListMapper.deleteCustomerById(id);
        sqlSession.commit();
        return code;
    }

    //修改客户信息
    @RequestMapping("editcustom")
    @ResponseBody
    public int editcustom(Custom custom) {
        if (custom.getName() != null) {
            SqlSessionFactory ssf = null;
            try {
                InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
                ssf = new SqlSessionFactoryBuilder().build(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SqlSession sqlSession = ssf.openSession();
            CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
            System.out.println(custom);
            int result_code = customListMapper.updateCustomerInfo(custom);
            sqlSession.commit();
            if (result_code == 1) {
                System.out.println("修改客户成功！");
                return 1;
            }else {
                System.out.println("修改客户失败！");
                return 0;
            }
        }
        return 0;
    }

    //准确查询客户订单信息-根据customid准确查询
    @PostMapping(value = "selectorderlistBycustomid", produces = "application/json")
    @ResponseBody
    public List<Orderlist> selectorderlistBycustomid(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        OrderListMapper orderListMapper = sqlSession.getMapper(OrderListMapper.class);
        int customid = Integer.parseInt(request.getParameter("customid"));
        List<Orderlist> orderlists = orderListMapper.selectOrderlistByCustomid(customid);
        return orderlists;
    }

    //添加订单信息
    @RequestMapping("addorder")
    @ResponseBody
    public void addorder(Orderlist orderlist) {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        OrderListMapper orderListMapper = sqlSession.getMapper(OrderListMapper.class);

        // 获取当前时间的时间戳（毫秒）
        long currentTimeMillis = System.currentTimeMillis();
        // 加上 22 毫秒
        long newTimeMillis = currentTimeMillis + orderlist.getCustomid();
        // 将新的时间戳转换为 String 类型
        String timeStampString = String.valueOf(newTimeMillis);
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期时间
        String formattedDateTime = now.format(formatter);

        Orderlist orderlist1 = new Orderlist();
        orderlist1.setCustomid(orderlist.getCustomid());
        orderlist1.setOrderid("LJL" + timeStampString);
        orderlist1.setOrdernum(orderlist.getOrdernum());
        orderlist1.setOrderdatetime(formattedDateTime);
        orderListMapper.insertorder(orderlist1);
        sqlSession.commit();

    }


//    @RequestMapping("/uploadfile")
//    public String uploadfile(){
//        return "uploadfile";
//    }
//    //    头像上传
//    @RequestMapping("/uploadImg")
//    public void uploadImg(MultipartFile imgfile) throws IOException {
//        String oldName = imgfile.getOriginalFilename();
//        String suffix = oldName.substring(oldName.lastIndexOf("."));
//        String newName = UUID.randomUUID() + suffix;
//        imgfile.transferTo(new File("/Users/ljl/Documents/JavaEE/Spring_MVC_class9/target/Spring_MVC_class9/img/" + newName));
//        img_url = "img/" + newName;
//        System.out.println(newName);
//    }
//
//    //    简历上传
//    @RequestMapping("/uploadjl")
//    public void uploadjl(MultipartFile jlfile) throws IOException {
//        String oldName = jlfile.getOriginalFilename();
//        String suffix = oldName.substring(oldName.lastIndexOf("."));
//        String newName = UUID.randomUUID() + suffix;
//        jlfile.transferTo(new File("/Users/ljl/Documents/JavaEE/Spring_MVC_class9/target/Spring_MVC_class9/jl/" + newName));
//        jl_url = "jl/" + newName;
//        System.out.println(newName);
//    }
//    //文件下载
//    @RequestMapping("/download")
//    public ResponseEntity<byte[]> filedownload(HttpServletRequest request, String filename) throws Exception {
//        String path = request.getServletContext().getRealPath("/文件所在路径/");
//        File file = new File(path+File.separator+filename);
//        HttpHeaders headers = new HttpHeaders();
//
//
//    }

    //验证码调取code和url
    @GetMapping("/getyzm")
    @ResponseBody
    public Imgyzm getyzm() {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        YzmMapper yzmMapper = sqlSession.getMapper(YzmMapper.class);
        Random random = new Random();
        int randomNumber = random.nextInt(101); // 生成0-100之间的随机数
        Imgyzm imgyzm = yzmMapper.getyzm(randomNumber);
        sqlSession.commit();
        System.out.println(imgyzm);
        yzm_code = imgyzm.getMsgcode();
        return imgyzm;
    }

    @PostMapping("/requestyzm")
    @ResponseBody
    public int requestyzm(String result_code) {
        if (result_code.equals(yzm_code)){
            return 1;
        }else {
            return 0;
        }
    }

    //TODO 登录校验
    @PostMapping("/loginUser")
    @ResponseBody
    public int loginUser(AdminUser adminUser) {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //可使用Exception进行捕获
//        try {
////              用来抛出异常对象
//            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
//            ssf = new SqlSessionFactoryBuilder().build(input);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            System.out.println("this is finally");
//            System.out.println("不管运行是否成功，都会执行Finally这一句");
//        }

        SqlSession sqlSession = ssf.openSession();
        AdminUserMapper adminUserMapper = sqlSession.getMapper(AdminUserMapper.class);
        AdminUser adminUser_reslut = adminUserMapper.loginForUsername(adminUser);
        if (adminUser_reslut != null){
            return 1;
        }else {
            return 0;
        }
    }


    //TODO 注册事物提交
    @PostMapping("/registerUser")
    @ResponseBody
    public int registerUser(AdminUser adminUser) {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        AdminUserMapper adminUserMapper = sqlSession.getMapper(AdminUserMapper.class);
        int result_code = adminUserMapper.addAdminUser(adminUser);
        sqlSession.commit();
        System.out.println(result_code);
        return result_code;
    }

    @RequestMapping ("/test")
    public String test() {
        return "test";
    }

    private String minioUrl = "http://127.0.0.1:8091";

    private String accessKey = "pjl";

    private String secretKey = "pjlABC123";

    private String bucketName = "mybucket";

    @PostMapping("/uploadImg1")
    @ResponseBody
    public String uploadImg1(@RequestParam("imgfile") MultipartFile imgfile) {
        System.out.println("图片已上传");
        try {
            // 获取原始文件名
            String oldName = imgfile.getOriginalFilename();
            // 获取文件后缀
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            // 生成新的文件名
            String newName = "class11_img_file/img/" + UUID.randomUUID().toString() + suffix;

            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl) // 使用从配置文件中读取的URL
                    .credentials(accessKey, secretKey) // 使用从配置文件中读取的凭证
                    .build();

            // 将MultipartFile转换为输入流
            try (java.io.InputStream stream = imgfile.getInputStream()) {
                // 上传文件到MinIO
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName) // 使用从配置文件中读取的存储桶名称
                                .object(newName) // 对象名称（文件路径+文件名）
                                .stream(stream, imgfile.getSize(), -1) // 输入流、文件大小、-1表示不分片
                                .contentType(imgfile.getContentType()) // 内容类型
                                .build()
                );
            } catch (java.security.InvalidKeyException e) {
                throw new RuntimeException(e);
            }
            img_url = minioUrl + "/" + bucketName + "/" + newName;
            System.out.println(img_url);
            // 返回上传成功的文件路径
            return minioUrl + "/" + bucketName + "/" + newName;
        } catch (MinioException e) {
            // 处理MinIO异常
            return "Error occurred: " + e;
        } catch (IOException e) {
            // 处理IO异常
            return "Error occurred while reading the file: " + e;
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            // 处理密钥异常
            return "Error occurred with credentials: " + e;
        }
    }

    @PostMapping(value = "/uploadjl1")
    @ResponseBody
    public String uploadjl1(@RequestParam("jlfile") MultipartFile imgfile) {
        System.out.println("简历已上传");
        try {
            // 获取原始文件名
            String oldName = imgfile.getOriginalFilename();
            // 获取文件后缀
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            // 生成新的文件名
            String newName = "class11_img_file/file/" + UUID.randomUUID().toString() + suffix;

            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl) // 使用从配置文件中读取的URL
                    .credentials(accessKey, secretKey) // 使用从配置文件中读取的凭证
                    .build();

            // 将MultipartFile转换为输入流
            try (java.io.InputStream stream = imgfile.getInputStream()) {
                // 上传文件到MinIO
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName) // 使用从配置文件中读取的存储桶名称
                                .object(newName) // 对象名称（文件路径+文件名）
                                .stream(stream, imgfile.getSize(), -1) // 输入流、文件大小、-1表示不分片
                                .contentType(imgfile.getContentType()) // 内容类型
                                .build()
                );
            } catch (java.security.InvalidKeyException e) {
                throw new RuntimeException(e);
            }

            jl_url = minioUrl + "/" + bucketName + "/" + newName;
            System.out.println(jl_url);
            // 返回上传成功的文件路径
            return minioUrl + "/" + bucketName + "/" + newName;
        } catch (MinioException e) {
            // 处理MinIO异常
            return "Error occurred: " + e;
        } catch (IOException e) {
            // 处理IO异常
            return "Error occurred while reading the file: " + e;
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            // 处理密钥异常
            return "Error occurred with credentials: " + e;
        }
    }


    @GetMapping("axiosTest")
    public String axiosTest() {
        return "axiosTest";
    }

    @GetMapping("testt")
    @ResponseBody
    public int testt(){
        return 2233;
    }






}
